package com.duck.user.controller;

import com.duck.common.domain.Result;
import com.duck.user.config.JwtProperties;
import com.duck.user.domain.dto.ChangePasswordDto;
import com.duck.user.domain.dto.LoginDto;
import com.duck.user.domain.po.UserPojo;
import com.duck.user.service.UserService;
import com.duck.user.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Objects;


@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class LoginController {

    private final JwtTool jwtTool;

    private final UserService userService;

    private final JwtProperties jwtProperties;

    /**
     * 登录操作
     * @param user 前端传值
     * @return 状态码，token
     */
    @PostMapping("/login/")
    public Result login(@RequestBody LoginDto user) {
        //查询用户信息
        UserPojo queryUser = userService.checkUserByUsername(user.getUsername());
        //判断用户是否存在
        if (Objects.isNull(queryUser)) {
            throw new RuntimeException("用户名不存在,请确定是否注册过账号");
        }
        //认证通过 生成token
        String token = jwtTool.createToken(Long.valueOf(queryUser.getUserId()), jwtProperties.getTokenTTL());
        UserPojo userPojo = userService.checkUserByUsername(user.getUsername());
        Integer userType = userPojo.getUserType();
        // 返回token
        HashMap<String, Object> returnData = new HashMap<>() {{
            put("token", token);
            put("user_type",userType);
        }};
        return new Result(returnData,200 , "请求通过");
    }

    /**
     * 退出登录
     * @return 状态码
     */
    @PostMapping("/logout/")
    public Result logout() {
        return new Result(200,"退出成功");
    }

    /**
     * 登录前忘记密码
     * @param user 前端入参
     * @return 状态码
     */
    @PostMapping("/changePassword/")
    public Result LoginAlterPassword(@RequestBody ChangePasswordDto user){
        UserPojo a = userService.checkEmail(user.getEmail());
        if (Objects.isNull(a)) {
            return new Result(404,"账号不存在");
        }
        if (!user.getNewPassword().equals(user.getConfirmPassword())) {
            return new Result(404, "两次密码输入不一致");
        }
        if (user.getCode().isEmpty()) {
            return new Result(404, "请输入验证码");
        }
        //替换密码，把新密码加密
        HashMap<String, Object> insertData = new HashMap<>() {{
            put("email", user.getEmail());
            put("newPassword", BCrypt.hashpw(user.getNewPassword(), BCrypt.gensalt()));
        }};
        userService.changePassword(insertData);
        return new Result(200,"修改成功");
    }
}